package com.bucks.service;

import com.bucks.bean.Coffee;
import com.bucks.bean.CoffeeOrder;
import com.bucks.bean.OrderState;
import com.bucks.repository.CoffeeOrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**

 * @date 2019-11-29
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class CoffeeOrderService {

    @Autowired
    private CoffeeOrderRepository orderRepository;

    public CoffeeOrder createOrder(String customer, Coffee ... coffees){
        CoffeeOrder order = CoffeeOrder.builder()
                .customer(customer)
                .items(Arrays.asList(coffees))
                .state(OrderState.INIT)
                .build();
        CoffeeOrder saved = orderRepository.save(order);
        log.info("New Order: {}",saved);
        return saved;
    }

    public boolean updateState(CoffeeOrder coffeeOrder,OrderState state){
        if (state.compareTo(coffeeOrder.getState())<=0){
            log.warn("Wrong State order: {}, {}",state,coffeeOrder.getState());
            return false;
        }
        coffeeOrder.setState(state);
        orderRepository.save(coffeeOrder);
        log.info("Updated Order: {}",coffeeOrder);
        return true;
    }
}
